﻿using System;
using System.Web.Mvc;
using MvcGraffiti.Core;
using MvcGraffiti.Models;

namespace MvcGraffiti.Controllers
{
    public class GraffitisController : Controller
    {
    	public const string UserSessionKey = "_sessionIdKey";

		private GraffitiRepository _repository;
    	private GraffitiRepository Repository
    	{
    		get
    		{
    			if(_repository==null)
					_repository = new GraffitiRepository();

    			return _repository;
    		}
			set { _repository = value; }
    	}

		protected override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			base.OnActionExecuting(filterContext);

            ViewModel.UserName = UserName;
			ViewModel.SessionId = SessionId;

            // dynamicでデリゲート渡し！
			ViewModel.CurrentIp = (Func<string>) (() => HttpContext.Request.ServerVariables["LOCAL_ADDR"]);
		}

    	private string UserName
    	{
    		get { return Repository.GetUserName(SessionId); }
    	}

		private int SessionId
		{
			get { return (int?)Session[UserSessionKey] ?? 0; }
			set { Session[UserSessionKey] = value; }
		}
		
        public ActionResult Index(int? id)
        {
            if (id.HasValue)
            {
                ViewModel.GraffitiId = id;
                return View("View");
            }

            return View("List");
        }

		[HttpPost]
		public ActionResult Index(string name)
		{
			if (string.IsNullOrWhiteSpace(name))
			{
				ModelState.AddModelError("name","名前いれてね！");
				return Index(default(int?));
			}

			SessionId = Repository.CreateSession(name);
			return RedirectToAction("Index");
		}

		public ActionResult Thumbnail(int id)
		{
			var path = Server.MapPath("~/App_Data/Thumbnails/" + id + ".png");
			if(!System.IO.File.Exists(path))
			{
				// Thumbnailの生成
				var graffiti = Repository.GetGraffiti(id);
				// 600*800を150*200に。
				ThumbnailGenerator.Generate(600, 800, graffiti.Strokes, 0.25m, path);
			}

			return File(path, "image/png");
		}
    }
}
